package cn.itcast.jdbc;

import cn.itcast.util.JDBCUtil;

import java.sql.*;

public class JDBCDemo10 {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        ResultSet rs = null;

        try {
            //获取连接
            conn = JDBCUtil.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            //定义SQL
            //zhangsan - 500
            String sql1 = "UPDATE account SET balance = balance - ? WHERE id = ?";
            //lisi + 500
            String sql2 = "UPDATE account SET balance = balance + ? WHERE id = ?";
            //执行SQL对象
            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);
            //设置参数
            pstmt1.setDouble(1,500);
            pstmt1.setInt(2,1);
            pstmt2.setDouble(1,500);
            pstmt2.setInt(2,2);
            //执行SQL
            pstmt1.executeUpdate();
            //添加异常
            int a = 1/0;
            pstmt2.executeUpdate();
            //提交事务
            conn.commit();
        } catch (Exception e) {
            try {
                //回滚事务
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCUtil.Close(pstmt1,conn);
            JDBCUtil.Close(pstmt2,null);
        }
    }

}
